<?php
namespace app\admin\controller;

class Banner extends Common
{
    private $obj;
    public function _initialize()
    {
        parent::_initialize();
        $this->obj = model('Banner');
    }

    public function index()
    {
        $where = [];
        $data = $this->obj->getList($where);
        $this->assign('data', $data);
        return view();
    }

    public function save_banner() {
        $id = input('param.id', 0);
        if (request()->isPost()) {
            /**
             * 组装数据
             */
            $data['name'] = input('post.name', '');
            $data['url'] = input('post.url', '');
            $data['image'] = input('post.image', '');

            /**
             * 验证数据
             */
            $validate = validate('Banner');
            if(!$validate->check($data)) {
                $this->error($validate->getError());
            }

            /**
             * 保存数据
             */
            $where = $id > 0 ? ['id' => $id] : [];
            $rs = $this->obj->save($data, $where);

            // 清理缓存
            \app\api\service\Base::clear_cache();

            if ($rs) {
                $this->success('保存成功', '');
            } else {
                $this->error('保存失败');
            }
        } else{
            $data = [];
            if ($id > 0) {
                $data = $this->obj->get(['id' => $id]);
            }
            $this->assign('data', $data);
            return view();
        }
    }

    /**
     * 修改模型字段值
     */
    public function save_brand_field() {
        $model = $this->obj;
        $rs = save_model_field($model);
        if ($rs) {
            $this->success('修改成功', null, '', 1);
        } else {
            $this->error('修改失败');
        }
    }
}
